<template>
	<div class="shopcart-container">
		<!-- 收货地址区域 -->
		<van-cell title="收货地址" is-link :to="{ name: 'addressList', params: { addressId: address.id } }"
			class="address-cell">
			<template #label>
				<div class="address-info">
					<div>姓名：{{ address.name }}</div>
					<div>电话：{{ address.tel }}</div>
					<div>地址：{{ address.city + address.county + address.address_detail }}</div>
				</div>
			</template>
		</van-cell>

		<div class="goods-list-container">
			<!-- 直接使用本地图片路径 -->
			<van-card v-for="item in goodsList" :key="item.id" :num="item.count" :price="item.price" :title="item.title"
				:desc="item.title" :thumb="item.pic" class="goods-card" />
		</div>
		<!-- 配送信息 -->
		<van-cell title="配送服务" label="快递运输,工作日、双休日与节假日均可送货" class="delivery-cell" />

		<van-field v-model="remark" rows="2" autosize label="订单备注" type="textarea" placeholder="请输入订单备注"
			class="remark-field" />

		<!-- 运费信息 -->
		<div class="fee-info-container">
			<van-cell title="商品金额" :value="`¥${amount.toFixed(2)}`" class="fee-cell" />
			<van-cell title="运费" :value="`¥0.00`" class="fee-cell" />
			<van-cell title="总价" :value="`¥${amount.toFixed(2)}`" class="fee-cell" />
		</div>
		<!-- 创建订单按钮 -->
		<van-button @click="OnClickCreateOrder" size="large" type="primary" class="create-order-button">
			创建订单
		</van-button>
	</div>
</template>

<script>
import { showToast } from 'vant';
import { createOrderAPI } from "@/api/order.js";
import { getDefaultAddressAPI } from "@/api/address.js";
import { getCartListCheckedAPI } from "@/api/cart.js";

export default {
    data() {
        return {
            goodsList: [],
            remark: "",
            amount: 0,
            address: {},
        };
    },
    created() {
        if (this.$route.params.addressId) {
            this.address.id = this.$route.params.addressId;
        }
        this.initDefaultAddress(); 
        this.initSelectedGoods(); 
    },
    methods: {
        initSelectedGoods() {
            const selectedItems = JSON.parse(localStorage.getItem('selectedCartItems'));
            if (selectedItems) {
                this.goodsList = selectedItems;
                this.amount = 0;
                this.goodsList.forEach((item) => {
                    this.amount += item.count * item.price;
                });
            }
        },
        initDefaultAddress() {
            getDefaultAddressAPI(this.address.id).then(result => {
                if (result.data.length == 1) {
                    this.address = result.data[0];
                } else {
                    showToast("请先添加收货地址");
                    this.$router.replace({
                        name: "addressList",
                        params: {
                            addressId: 9999999999
                        }
                    });
                }
            });
        },
        saveOrderToLocalStorage(orderData) {
            try {
                let orderHistory = JSON.parse(localStorage.getItem('orderHistory')) || [];
                orderHistory.push(orderData);
                localStorage.setItem('orderHistory', JSON.stringify(orderHistory));
                console.log('订单已保存到本地存储');
            } catch (error) {
                console.error('保存订单到本地存储失败:', error);
            }
        },
        OnClickCreateOrder() {
            let productList = [];
            this.goodsList.forEach((item) =>
                productList.push({
                    product_id: item.product_id,
                    count: item.count,
                    price: item.price,
                })
            );
            let params = {
                address_id: this.address.id,
                productList: productList,
                remark: this.remark,
            };
            createOrderAPI(params).then(result => {
                showToast(result.msg);
                const orderData = {
                    id: new Date().getTime(), 
                    address: this.address,
                    products: this.goodsList,
                    amount: this.amount,
                    remark: this.remark,
                    createTime: new Date().toISOString(),
                    status: 0 
                };
                this.saveOrderToLocalStorage(orderData);
                this.$router.push({
                    name: "orderList"
                });
                localStorage.removeItem('selectedCartItems');
            });
        },
    },
};
</script>
<style lang="less" scoped>
	@bg-color: #f4f4f4;
	@card-bg-color: #fff;
	@primary-color: #007bff;
	@text-color: #333;

	.shopcart-container {
		display: flex;
		flex-direction: column;
		background: @bg-color;
		padding: 15px;

		.address-cell {
			background-color: @card-bg-color;
			border-radius: 10px;
			box-shadow: 0 0.2rem 0.5rem rgba(0, 0, 0, 0.1);
			margin-bottom: 15px;

			.address-info {
				font-size: 16px;
				color: @text-color;
			}
		}

		.goods-list-container {
			margin-bottom: 15px;

			.goods-card {
				margin-bottom: 10px;
				border-radius: 10px;
				box-shadow: 0 0.2rem 0.5rem rgba(0, 0, 0, 0.1);
				background-color: @card-bg-color;

				.van-card__title {
					font-size: 18px;
					color: @text-color;
				}
			}
		}

		.delivery-cell {
			background-color: @card-bg-color;
			border-radius: 10px;
			box-shadow: 0 0.2rem 0.5rem rgba(0, 0, 0, 0.1);
			margin-bottom: 15px;
		}

		.remark-field {
			background-color: @card-bg-color;
			border-radius: 10px;
			box-shadow: 0 0.2rem 0.5rem rgba(0, 0, 0, 0.1);
			margin-bottom: 15px;
		}

		.fee-info-container {
			margin-bottom: 15px;

			.fee-cell {
				background-color: @card-bg-color;
				border-radius: 10px;
				box-shadow: 0 0.2rem 0.5rem rgba(0, 0, 0, 0.1);
				margin-bottom: 10px;
			}
		}

		.create-order-button {
			background-color: @primary-color;
			border-radius: 10px;
			box-shadow: 0 0.2rem 0.5rem rgba(0, 0, 0, 0.1);
			font-size: 18px;
			font-weight: bold;
			transition: all 0.3s ease;

			&:hover {
				background-color: #0056b3;
				transform: translateY(-2px);
			}
		}
	}
</style>